﻿/// <reference path="jquery-vsdoc.js" />
/// <reference path="jquery-ui-1.8.custom.min.js" />

Object.count = function (aObject) {
    var i = 0;
    for (var item in aObject) {
        if (aObject[item]) i++;
    }
    return i;
};


/*
*
*string:原始字符串
*substr:子字符串
*isIgnoreCase:忽略大小写
*/
String.prototype.contains = function (substr, isIgnoreCase) {
    var string = this;
    if (isIgnoreCase) {
        string = string.toLowerCase();
        substr = substr.toLowerCase();
    }
    var startChar = substr.substring(0, 1);
    var strLen = substr.length;
    for (var j = 0; j < string.length - strLen + 1; j++) {
        if (string.charAt(j) == startChar)//如果匹配起始字符,开始查找
        {
            if (string.substring(j, j + strLen) == substr)//如果从j开始的字符与str匹配，那ok
            {
                return true;
            }
        }
    }
    return false;
}

$.getQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
} 



// Based on Jquery
$.prototype.comboxBindingIn = function (data, displayField, valueField) {
    var selectControl = $("<select/>");
    $(data).each(function (index, item) {
        $('<option/>').val(item[valueField]).html(item[displayField]).appendTo(selectControl);
    });
    this.append(selectControl);
    return this;
};
$.prototype.comboxBinding = function (data, displayField, valueField) {
    var selectControl = this.empty();
    $(data).each(function (index, item) {
        $('<option/>').val(item[valueField]).html(item[displayField]).appendTo(selectControl);
    });
    return this;
};
$.prototype.comboxBindingWithEmptyDefault = function (data, displayField, valueField, defaultEmptyText, defaultEmptyValue) {
    var selectControl = this.empty();
    var emptyItem = $('<option/>');
    if (defaultEmptyText) {
        emptyItem.val(defaultEmptyValue).html(defaultEmptyText);
    }
    emptyItem.appendTo(selectControl);
    $(data).each(function (index, item) {
        $('<option/>').val(item[valueField]).html(item[displayField]).appendTo(selectControl);
    });
    return this;
};
$.prototype.comboxBindingWithArray = function (data) {
    var selectControl = this.empty();
    $(data).each(function (index, item) {
        $('<option/>')
.val(item)
.html(item)
.appendTo(selectControl);
    });
    return this;
};

$.AsyncMethod = function (url,methodType) {
    return function returnMethod(callback,args, beforeCallback, afterCallback) {
        if (beforeCallback) beforeCallback();

        if (methodType && methodType.toLowerCase() == 'post')
            $.post(
                url,
                args,
                 function (e) {
                     callback(e);
                     if (afterCallback) afterCallback();
                 });           
            
        else
            $.getJSON(
                    url,
                    args,
                    function (e) {
                        callback(e);
                        if (afterCallback) afterCallback();
                    });
    };
};

$.SyncMethod = function (url, methodType) {
    return function returnMethod(callback, args, beforeCallback, afterCallback) {
        if (beforeCallback) beforeCallback();

        if (methodType && methodType.toLowerCase() == 'post') {
            $.ajax({
                url: url,   //接收页面
                type: 'post',      //POST方式发送数据
                async: false,      //ajax同步
                data: args,
                dataType: 'json',
                success: function (e) {
                        callback(e);
                        if (afterCallback) afterCallback();
                    }
                });
         } else {
            $.ajax({
                url: url,  
                type: 'get',
                async: false,
                data: args, 
                dataType: 'json',
                success: function (e) {
                        callback(e);
                        if (afterCallback) afterCallback();
                    }
                });
         }
    };
};


/*---- Datetime 相关方法 --*/

/**
* 对Date的扩展，将 Date 转化为指定格式的String
* 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
* 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
* eg:
* (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2007-07-02 08:09:04.423
* (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2007-03-10 二 20:09:04
* (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2007-03-10 周二 08:09:04
* (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2007-03-10 星期二 08:09:04
* (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2007-7-2 8:9:4.18
*/
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        //月份
        "d+": this.getDate(),
        //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12,
        //小时
        "H+": this.getHours(),
        //小时
        "m+": this.getMinutes(),
        //分
        "s+": this.getSeconds(),
        //秒
        "q+": Math.floor((this.getMonth() + 3) / 3),
        //季度
        "S": this.getMilliseconds() //毫秒
    };
    var week = {
        "0": "\u65e5",
        "1": "\u4e00",
        "2": "\u4e8c",
        "3": "\u4e09",
        "4": "\u56db",
        "5": "\u4e94",
        "6": "\u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

//2011-02-03 03:05          ToFullDateTime
Date.prototype.toFullDateTime = function () {
    return this.format("yyyy-MM-dd HH:mm");
}

//02-03 03:05           ToShortDateTime
Date.prototype.toShortDateTime = function () {
    return this.format("MM-dd HH:mm");
}

//2011-02-03                   ToFullDate
Date.prototype.toFullDate = function () {
    return this.format("yyyy-MM-dd");
}

//03:05:33              ToFullTime
Date.prototype.toFullTime = function () {
    return this.format("HH:mm:ss");
}

//星期六                ToDayOfWeek
Date.prototype.toDayOfWeek = function () {
    return this.format("EEE");
}

//2011-02-03 星期六     ToFullDateAndDay
Date.prototype.toFullDateAndDay = function () {
    return this.format("yyyy-MM-dd EEE");
}

//刚刚,x天前 之类                  ToNiceTime
Date.prototype.toNiceTime = function () {
    var now = new Date();
    var totalSecond = Math.floor((now - this) / 1000);
    if (totalSecond < 60) {
        return "刚刚";
    }

    var totalMinute = Math.floor(totalSecond / 60);
    if (totalMinute < 60) {
        return totalMinute + " 分钟前";
    }

    var dayDiff = Math.floor(totalMinute / 60 / 24);
    var yearDiff = Math.floor(dayDiff / 365);
    if (dayDiff == 0) {
        var totalHour = Math.floor(totalMinute / 60);
        return totalHour + " 小时前";
    }
    if (dayDiff == 1) {
        return "昨天 " + this.format("HH:mm");
    }
    if (dayDiff == 2) {
        return "前天 " + this.format("HH:mm");
    }
    if (yearDiff == 0) {
        return this.toShortDateTime();
    }
    return this.toFullDateTime();
}


// String转换成Date格式
String.prototype.toDateTime = function () {
    if (this.indexOf(".") > 0) {
        var data = this.split('.');
        return new Date(data[0], data[1] - 1, data[2]);
    }
    else if (this.indexOf("-") > 0) {
        var data = this.split('-');
        return new Date(data[0], data[1] - 1, data[2]);
    }
    else if (this.indexOf("/") > 0) {
        var data = this.split('/');
        return new Date(data[2], data[0] - 1, data[1]);
    }
}







String.prototype.htmlEncode = function () {
    var div = document.createElement("div");
    var text = document.createTextNode(this);
    div.appendChild(text);

    return div.innerHTML;
}

String.prototype.htmlDecode = function () {
    var div = document.createElement('div');
    div.innerHTML = this;

    return div.innerText;
}

String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}


///字符串匹配
String.prototype.startWith = function (str) {
    if (str == null || str == "" || this.length == 0 || str.length > this.length)
        return false;
    if (this.substr(0, str.length) == str)
        return true;
    else
        return false;
    return true;
}


//取出字符串头空格
//String.prototype.trim = function () {
//    var str = this;
//    if (str.charAt(0) == " " || str.charAt(0) == "\n") {
//        str = str.slice(1);
//        str = Trim(str);
//    }
//    return str;
//}

Date.prototype.dateAdd = function (interval, number) {
    var d = this;
    var k = { 'y': 'FullYear', 'q': 'Month', 'm': 'Month', 'w': 'Date', 'd': 'Date', 'h': 'Hours', 'n': 'Minutes', 's': 'Seconds', 'ms': 'MilliSeconds' };
    var n = { 'q': 3, 'w': 7 };
    eval('d.set' + k[interval] + '(d.get' + k[interval] + '()+' + ((n[interval] || 1) * number) + ')');
    return d;
}
Date.prototype.dateDiff = function (interval, objDate2) {
    var d = this, i = {}, t = d.getTime(), t2 = objDate2.getTime();
    i['y'] = objDate2.getFullYear() - d.getFullYear();
    i['q'] = i['y'] * 4 + Math.floor(objDate2.getMonth() / 4) - Math.floor(d.getMonth() / 4);
    i['m'] = i['y'] * 12 + objDate2.getMonth() - d.getMonth();
    i['ms'] = objDate2.getTime() - d.getTime();
    i['w'] = Math.floor((t2 + 345600000) / (604800000)) - Math.floor((t + 345600000) / (604800000));
    i['d'] = Math.floor(t2 / 86400000) - Math.floor(t / 86400000);
    i['h'] = Math.floor(t2 / 3600000) - Math.floor(t / 3600000);
    i['n'] = Math.floor(t2 / 60000) - Math.floor(t / 60000);
    i['s'] = Math.floor(t2 / 1000) - Math.floor(t / 1000);
    return i[interval];
} 


Date.prototype.toFullChineseDateFormat = function () {
    var yy = this.getFullYear();
    var mon = this.getMonth() + 1;
    var da = this.getDate();
    var day = this.getDay();

    var date = yy + "年";
    if (mon < 10) date += '0';
    date += mon + "月";
    if (da < 10) date += '0';
    date += da + "日";
    var date = date + "&nbsp星期" + "日一二三四五六".charAt(day);
    return date;
}
Date.prototype.toFullTimeFormat = function () {

    var hh = this.getHours();
    var mm = this.getMinutes();
    var ss = this.getTime() % 60000;
    ss = (ss - (ss % 1000)) / 1000;
    var clock = hh + ':';
    if (mm < 10) clock += '0';
    clock += mm + ':';
    if (ss < 10) clock += '0';
    clock += ss;

    return clock;
}


Date.prototype.toFullTimeFormatWithoutSec = function () {

    var hh = this.getHours();
    var mm = this.getMinutes();
    var ss = this.getTime() % 60000;
    ss = (ss - (ss % 1000)) / 1000;
    var clock = hh + ':';
    if (mm < 10) clock += '0';
    clock += mm;

    return clock;
}

Date.prototype.toEpoch = function () {
    if (!this) return null;
    return Math.round(this.getTime() / 1000);
};
Date.fromEpoch = function (epoch) {
    if (!epoch) return null;
    return new Date(epoch * 1000);
};
Date.prototype.getDifferDayCount = function (targetDate) {
    return Math.abs((this - targetDate) / 86400000);
};
Date.prototype.getOnlyDate = function () {
    var yyyy = this.getFullYear();
    var MM = this.getMonth();
    var dd = this.getDate();
    return new Date(yyyy, MM, dd);
};

Date.prototype.addDays = function (n) {
    this.setDate(this.getDate() + 0 + n);
    return this;
}
Date.prototype.addMonths = function (n) {
    this.setMonth(this.getMonth() + 0 + n);
    return this;
}

jQuery.fn.center = function (absolute) {
    return this.each(function () {
        var t = jQuery(this);

        t.css({
            position: absolute ? 'absolute' : 'fixed',
            left: '50%',
            top: '50%',
            zIndex: '99'
        }).css({
            marginLeft: '-' + (t.outerWidth() / 2) + 'px',
            marginTop: '-' + (t.outerHeight() / 2) + 'px'
        });

        if (absolute) {
            t.css({
                marginTop: parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
                marginLeft: parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};


//templateStr 
//data
//fieldHandlers: handle the string to be replaced in templateStr
//example :
/*var qtipFieldHandlers = {
    'CreateOn': function (workitem) {
        return dateTimeHandler(workitem.CreateOn);
    },
    'FinishOn': function (workitem) {
        return dateTimeHandler(workitem.FinishOn);
    },
    'Project.Name': function (workitem) {
        return (!workitem.Project || workitem.Project == null) ? '' : workitem.Project.Name;
    },
    'Task.Name': function (workitem) {
        return (!workitem.Task || workitem.Task == null) ? '' : workitem.Task.Name;
    }
}; */
//那么模板中的 {CreateOn}替换的时候使用 handlers中提供的方法进行替换

//$.populateTemplate = function (templateStr, data, fieldHandlers) {
//    if (!fieldHandlers) fieldHandlers = {};

//    var content = templateStr;
//    var dataArray = templateStr.match(new RegExp(/{(\S+)}/g));
//    for (var q in dataArray) {
//        dataField = dataArray[q].substring(1, dataArray[q].length - 1);
//        var regex = new RegExp(dataArray[q], "g");
//        dataValue = fieldHandlers[dataField] ? fieldHandlers[dataField](data) : data[dataField];
//        content = content.replace(regex, dataValue);
//    }
//    return content;
//};

$.toJSON = function (o) {
    if (typeof (JSON) == 'object' && JSON.stringify)
        return JSON.stringify(o);

    var type = typeof (o);

    if (o === null)
        return "null";

    if (type == "undefined")
        return undefined;

    if (type == "number" || type == "boolean")
        return o + "";

    if (type == "string")
        return $.quoteString(o);

    if (type == 'object') {
        if (typeof o.toJSON == "function")
            return $.toJSON(o.toJSON());
        if (o.constructor === Date)
            return o.toEpoch();

        //        if (o.constructor === Date) {
        //            var month = o.getUTCMonth() + 1;
        //            if (month < 10) month = '0' + month;

        //            var day = o.getUTCDate();
        //            if (day < 10) day = '0' + day;

        //            var year = o.getUTCFullYear();

        //            var hours = o.getUTCHours();
        //            if (hours < 10) hours = '0' + hours;

        //            var minutes = o.getUTCMinutes();
        //            if (minutes < 10) minutes = '0' + minutes;

        //            var seconds = o.getUTCSeconds();
        //            if (seconds < 10) seconds = '0' + seconds;

        //            var milli = o.getUTCMilliseconds();
        //            if (milli < 100) milli = '0' + milli;
        //            if (milli < 10) milli = '0' + milli;

        //            return '"' + year + '-' + month + '-' + day + 'T' +
        //                             hours + ':' + minutes + ':' + seconds +
        //                             '.' + milli + 'Z"';
        //        }

        if (o.constructor === Array) {
            var ret = [];
            for (var i = 0; i < o.length; i++)
                ret.push($.toJSON(o[i]) || "null");

            return "[" + ret.join(",") + "]";
        }

        var pairs = [];
        for (var k in o) {
            var name;
            var type = typeof k;

            if (type == "number")
                name = '"' + k + '"';
            else if (type == "string")
                name = $.quoteString(k);
            else
                continue;  //skip non-string or number keys

            if (typeof o[k] == "function")
                continue;  //skip pairs where the value is a function.

            var val = $.toJSON(o[k]);

            pairs.push(name + ":" + val);
        }

        return "{" + pairs.join(", ") + "}";
    }
};